<template>
  <div class="edit">
    <div class="height">
      <div class="title">{{ title }}</div>
      <div class="func">
        <el-button @click="save">保存</el-button>
        <el-button type="primary" @click="pulish">发布</el-button>
      </div>
    </div>
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" class="toolbar" />
    <div style="width: 100%;height: 50px;"></div>
    <div class="content">
      <el-input style="margin-top: 30px;" type="textarea" :autosize="{ minRows: 1 }" v-model="title"
        placeholder="请输入标题" />
      <Editor :defaultConfig="editorConfig" mode="default" v-model="valueHtml" @onCreated="handleCreated"
        style="height: calc(100% - 100px);" @onChange="onChange" />
    </div>
    <div class="wordCount">总字数：<span>{{ wordCount }}</span></div>
  </div>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import service from '../service/index';
import { ElLoading, ElMessage } from 'element-plus';
import { to } from '../plugin/index'
const { getChapter, addChapter, updatedChapter } = service;
import { IDomEditor } from '@wangeditor/editor';

const props = defineProps<{ bookId: string, id?: string, type: number, parentChaptersId?: string }>();
const { bookId, id, type, parentChaptersId } = props;

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')
const title = ref('')
const wordCount = ref<number>(0);
const contentString = ref<string>('');
const emit = defineEmits(['changeIsEdit']);

const save = () => {
  emit('changeIsEdit', false);
}

const pulish = async () => {
  if (type === 2) {
    // 有 id，走修改逻辑
    const params = {
      id,
      title: title.value,
      content: valueHtml.value,
      contentString: contentString.value,
    }
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(updatedChapter(params));
    loading.close();
    // dialogFormVisible.value = false;
    ElMessage.success('修改成功');
    const result = res.data;
    if (!err && result.code === 0) {
      emit('changeIsEdit', false);
    } else {
      ElMessage.error('修改数据失败');
      console.error(err);
    }
  } else if (type === 1 || type === 3) {
    // 没有 id，走新增逻辑
    const params = {
      bookId,
      title: title.value,
      type: 1,
      content: valueHtml.value,
      contentString: contentString.value,
      parentChaptersId,
    }
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(addChapter(params));
    loading.close();
    // dialogFormVisible.value = false;
    ElMessage.success('新增成功');
    const result = res.data;
    if (!err && result.code === 0) {
      emit('changeIsEdit', false);
    } else {
      ElMessage.error('新增数据失败');
      console.error(err);
    }
  }

}

const getChapterHandle = async () => {
  if (type === 2) {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getChapter({ id: id as string }));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
      title.value = result.data.title;
      valueHtml.value = result.data.content;
    } else {
      ElMessage.error('新增数据失败');
      console.error(err);
    }
  }
}

onMounted(() => {
  if (id) {
    getChapterHandle();
  }
})

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/chapters/uploadImage', // 图片上传的服务器地址
      fieldName: 'image', // 文件域的名称
      maxFileSize: 20 * 1024 * 1024, // 图片最大大小，单位 B，不配置则默认 2M
      maxNumberOfFiles: 5, // 最多可上传几个文件，不配置则默认 10 个
      headers: {
        // 自定义请求头
      },
      withCredentials: false, // 跨域是否带上凭证，默认是false
      timeout: 5 * 60 * 1000, // 超时时间，默认为 5 分钟
      meta: {
        // 上传额外参数
      },
    },
    uploadVideo: {
      server: '/api/chapters/uploadVideo', // 图片上传的服务器地址
      fieldName: 'video', // 文件域的名称
      maxFileSize: 2048 * 1024 * 1024, // 图片最大大小，单位 B，不配置则默认 2g
      maxNumberOfFiles: 5, // 最多可上传几个文件，不配置则默认 5 个
      headers: {
        // 自定义请求头
      },
      withCredentials: false, // 跨域是否带上凭证，默认是false
      timeout: 5 * 60 * 1000, // 超时时间，默认为 5 分钟
      meta: {
        // 上传额外参数
      },
    },
  },
}

const onChange = (editor: IDomEditor) => {
  const text = editor.getText();
  wordCount.value = text.length;
  contentString.value = text;
}

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return

  editor.destroy()
})

// 编辑器回调函数
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
<style lang="less" scoped>
.edit {
  height: 100%;

  .height {
    display: flex;
    justify-content: space-between;
    height: 50px;
    padding: 0 20px;
    border-bottom: 1px solid #0000000a;

    .title {
      color: #585a5a;
    }
  }

  .toolbar {
    position: fixed;
    top: 70px;
    left: 370px;
    // right: 45px;
    right: 0;
    z-index: 1000;
    border-bottom: 1px solid #0000000a;
  }
}

.content {
  width: 70%;
  overflow-y: hidden;
  height: calc(100% - 100px);
  margin: 0 auto;
}

.wordCount {
  position: fixed;
  bottom: 10px;
  width: 70%;
  margin: 0 auto;
}

::v-deep(.el-textarea__inner) {
  font-size: 36px;
  font-weight: 700;
  border: none;
  outline: none;
  box-shadow: none;
  resize: none;
}

::v-deep(.w-e-toolbar) {
  // position: fixed;
  // top: 20px; /* 距离页面顶部的距离 */
  // left: 370px; /* 距离页面左边的距离 */
  // right: 0; /* 距离页面右边的距离，使工具栏宽度适应整个视口宽度 */
  // z-index: 1000; /* 确保工具栏位于其他内容之上 */
  justify-content: center;
}
</style>